package com.jielihaofeng.nio.writable;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * @author Johnnie Wind
 * @description 可写事件处理
 * @date 2021/11/8 14:04
 */
public class Server {

    public static void main(String[] args) throws IOException {

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8080));

        Selector selector = Selector.open();
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT,null);

        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                iterator.remove();

                if (key.isAcceptable()){
//                    ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                    SocketChannel sc = serverSocketChannel.accept();
                    sc.configureBlocking(false);
                    SelectionKey scKey = sc.register(selector, 0, null);
                    scKey.interestOps(SelectionKey.OP_READ);

                    // 向客户端发送大量数据
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < 5000000; i++) {
                        sb.append("a");
                    }
                    ByteBuffer buffer = Charset.defaultCharset().encode(sb.toString());

                    // 返回一个实际写入的字节数
                    int write = sc.write(buffer);
                    System.out.println(write);

//                    // 方式一：判断buffer是否还有内容没写
//                    while (buffer.hasRemaining()) {
//                        // 这样做虽然可以，但是不好，存在写缓冲区满了还一直循环写，但又写不进去的情况
//                        int write1 = sc.write(buffer);
//                        System.out.println(write1);
//                    }

                    // 方式二：判断buffer是否还有内容没写
                    if (buffer.hasRemaining()) {
                        // 关注可写事件，在原来关注事件的基础上scKey.interestOps()
                        scKey.interestOps(scKey.interestOps() + SelectionKey.OP_WRITE);
                        // 未写完的数据挂到SelectionKey
                        scKey.attach(buffer);
                    }
                }else if (key.isWritable()){
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    SocketChannel sc = (SocketChannel) key.channel();
                    int write = sc.write(buffer);
                    System.out.println(write);
                    if (!buffer.hasRemaining()) {
                        // 取消关注可写事件
                        key.interestOps(key.interestOps() - SelectionKey.OP_WRITE);
                        // 清除附件
                        key.attach(null);
                    }
                }
            }
        }
    }
}
